package persistent.prestige.console.netty.dubbo.net;

import java.util.List;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import persistent.prestige.console.netty.dubbo.utils.LogUtils;

/**
 * 响应信息解码器  用于客户端
 * @author dingwei2
 * 
 * 响应报文格式
 * 4字节的请求序列号 2字节的执行状态码 2字节数据长度 多字节的响应数据信息(data)
 *
 */
public class ResponseFrameDecoder extends ByteToMessageDecoder {
	private static final int HEAD_LENGTH = 8;

	@Override
	protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
		
		LogUtils.log("ResponseFrameDecoder start calling....");
		
		// TODO Auto-generated method stub
		int r = in.readableBytes();
		
		LogUtils.log("ResponseFrameDecoder 累积缓存区中可读长度:%d", r);
		
		if(r < HEAD_LENGTH ) {
			LogUtils.log("ResponseFrameDecoder 当前累积缓存区可读数据长度为%d,小于协议头的长度%d", r, HEAD_LENGTH);
			return;
		}
		
		int currentReaderIndex = in.readerIndex();
		int requestId = in.getInt(currentReaderIndex); // 0-3 4个字节
		short code = in.getShort(currentReaderIndex + 4);  // 4,5
		short contentLength = in.getShort(currentReaderIndex + 6); //响应数据长度
		
		LogUtils.log("ResponseFrameDecoder requestId:%d,code:%d,contentLength:%d", requestId, code, contentLength);
		
		
		int packetLen;
		
		if( r < (packetLen = HEAD_LENGTH + contentLength))  {
			LogUtils.log("ResponseFrameDecoder 可读长度:%d,需要包长度:%d", r, packetLen);
			return;
		}
			
		in.skipBytes( HEAD_LENGTH );
		
		
		String data;
		if(contentLength > 0 ) {
			byte[] dst = new byte[contentLength];
			in.readBytes(dst, 0, contentLength);
			data = new String(dst);
		} else {
			data = "";
		}
		
		
		out.add(new Response(requestId, code, new String(data)));
		LogUtils.log("ResponseFrameDecoder 成功解析服务端响应信息并准备给下游处理器处理");

	}

}
